package com.wei.myhame.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.wei.myhame.base.interfaces.IBaseView;
import com.wei.myhame.base.interfaces.IPresenter;
import com.wei.myhame.utils.SystemUtils;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment <P extends IPresenter> extends Fragment implements IBaseView {

    protected Context context;

    protected P presenter;
    protected View mView;

    private Unbinder unbinder;


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(presenter != null && isVisibleToUser){
            initData();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView= inflater.inflate(getLayout(),null);
        return mView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        this.context = getContext();
        unbinder = ButterKnife.bind(this,view);
        if(!SystemUtils.checkNetWork()){
            showNetWorkErorr();
        }else{
            presenter = createPresenter();
            if(presenter!=null){
                presenter.attachView(this);
            }
            initView();
            initData();
        }
    }


    protected abstract int getLayout();

    protected abstract P createPresenter();

    protected abstract void initView();

    protected abstract void initData();



    @Override
    public void showDataError(String tips) {

    }

    @Override
    public void showNetWorkErorr() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if(presenter != null){
            presenter.attachView(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(presenter != null){
            presenter.detachView();
            presenter = null;
        }
        if(unbinder != null){
            unbinder.unbind();
        }
    }
}
